package util;

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Cpf {
	private String cpf;
	
	public long getCpfLng() {
		long d;
		try {
			d = Long.parseLong(this.cpf);
		} catch (Exception e) {
			d = 0L;
		}
		return d;
	}
	
	public String getCpf() {
        return Util.format(this.getCpfStr(), "###.###.###/##");   
	}
	
	public String getCpfStr() {
		if (this.cpf == null) {
			return "";
		} else {
			return Util.formatZeroLeft(Long.valueOf(this.cpf),11);
		}
	}
	
	public void setCpf(String cpf) {
		String[] strs = { ".", "/", "-", " "};
	    for (String str : strs) 
	    	cpf = cpf.replace(str, "");
		this.cpf = cpf;
	}
	
	public void setCpf(Long cpf) {
		if(cpf == null) {
			this.cpf = null;
		} else {
			NumberFormat nf = new DecimalFormat("0");   
			nf.setMinimumIntegerDigits(11);   
			this.cpf = nf.format(Long.valueOf(cpf));
		}
	}
	
	public static boolean isValid(String cpfOrCnpj) {
		if (cpfOrCnpj == null) return false;
		if (cpfOrCnpj.equals("")) return false;
		String n = cpfOrCnpj.replaceAll("_","0");
		n = n.replaceAll("[^0-9]*","");
		if (n.trim().equals("")) return false;
		if(Long.parseLong(n) == 0) return false;
		boolean isCnpj = n.length() == 14;
		boolean isCpf = n.length() == 11;
		if (!isCpf && !isCnpj) return false;
		int i; int j;   // just count
		int digit;      // A number digit   
		int coeficient; // A coeficient     
		int sum;        // The sum of (Digit * Coeficient)   
		int[] foundDv = {0,0}; // The found Dv1 and Dv2   
		int dv1 = Integer.parseInt(String.valueOf(n.charAt(n.length()-2)));   
		int dv2 = Integer.parseInt(String.valueOf(n.charAt(n.length()-1)));         
		for (j = 0; j < 2; j++) {   
			sum = 0;   
			coeficient = 2;   
			for (i = n.length() - 3 + j; i >= 0 ; i--) {
				digit = Integer.parseInt(String.valueOf(n.charAt(i)));
				sum += digit * coeficient;
				coeficient ++;
				if (coeficient > 9 && isCnpj) coeficient = 2;
           }
			foundDv[j] = 11 - sum % 11;   
			if (foundDv[j] >= 10) foundDv[j] = 0;   
		}
		return dv1 == foundDv[0] && dv2 == foundDv[1];   
	}  
	
	public boolean isValid(){
		return Cpf.isValid(this.cpf);
	}
}
